<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { NButton, useMessage, NCard, NTabs, NTabPane, NSpace, NRow, NCol, NStatistic } from 'naive-ui';
import UpdatePassword from '../components/UpdatePassword.vue';
import ListStore from '../components/ListStore.vue';
import UserOrderBuyer from '../components/UserOrderBuyer.vue';
import UserOrderSeller from '../components/UserOrderSeller.vue';
import { changeTypeToSeller, queryUserType } from '../api/user';
import { getToken } from '../util/token';
import { handleNoToken } from '../util/handler';
import statusCode from '../api/statusCode';
import { getUserStatistics } from '../api/statistics';

const message = useMessage();

const isSeller = ref<boolean | undefined>(undefined);
const setIsSeller = async () => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return;
  }
  try {
    const resp = await queryUserType(token);
    if (resp.status === statusCode.SUCCESS) {
      isSeller.value = (resp.data.userType === 1); // 0 for customer, 1 for seller
    }
  } catch (error) {
    message.error('' + error);
  }
};


const handleChangeButton = async () => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return;
  }
  const resp = await changeTypeToSeller(token);
  if (resp.status === statusCode.SUCCESS) {
    message.success('变更成功', {
      duration: 1500,
      onAfterLeave: () => setIsSeller()
    });
  } else {
    message.error('变更失败', {
      onAfterLeave: () => setIsSeller()
    });
  }
};
const getStatisticInfo = async () => {
  const token = getToken();
  if (!token) {
    handleNoToken(message);
    return ({ pay: 0, time: 0 });
  }
  try {
    const resp = await getUserStatistics({ month: new Date().getMonth()+1, token});
    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else {
      throw new Error(`错误码：${resp.status}`);
    }
  } catch (error) {
    message.error('' + error);
    return ({ pay: 0, time: 0 });
  }
};

const moneyThisMonth = ref(0);
const numberThisMonth = ref(0);
const getStatistic = async () => {
  const { pay: spentMoney, time: purchaseNumber } = await getStatisticInfo();
  moneyThisMonth.value = spentMoney;
  numberThisMonth.value = purchaseNumber;
};

onMounted(() => {
  setIsSeller();
  getStatistic();
});

const statistic =
  computed(() => isSeller.value ?
    ({ firstLabel: '本月销售额', secondLabel: '本月交易次数' }) :
    ({ firstLabel: '本月消费', secondLabel: '本月消费次数' }));
</script>

<template>
  <n-card title="我的淘金">
    <n-space vertical>
      <n-row v-if="isSeller !== undefined">
        <n-col :span="12">
          <n-statistic
            :label="statistic.firstLabel"
            :value="moneyThisMonth"
          >
            <template #prefix>
              <span>￥</span>
            </template>
          </n-statistic>
        </n-col>
        <n-col :span="12">
          <n-statistic
            :label="statistic.secondLabel"
            :value="numberThisMonth"
          >
            <template #suffix>
              <span>次</span>
            </template>
          </n-statistic>
        </n-col>
      </n-row>
      <n-tabs
        default-value="order"
        type="segment"
      >
        <n-tab-pane
          name="order"
          tab="订单"
        >
          <div v-if="isSeller !== undefined">
            <user-order-seller v-if="isSeller" />
            <user-order-buyer v-else />
          </div>
        </n-tab-pane>
        <n-tab-pane
          name="account"
          tab="账号"
        >
          <n-space vertical>
            <n-button
              v-if="!isSeller"
              @click="handleChangeButton"
            >
              化身商家
            </n-button>
            <update-password />
          </n-space>
        </n-tab-pane>
        <n-tab-pane
          v-if="isSeller"
          name="store"
          display-directive="if"
          tab="商店"
        >
          <list-store />
        </n-tab-pane>
      </n-tabs>
      <div
        v-if="isSeller !== undefined"
        class="function change-type"
      >
        <p>{{ isSeller ? '商家' : '顾客' }}</p>
      </div>
    </n-space>
  </n-card>
</template>

<style scoped>
</style>
